<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    姓名：<input class="username" /><br />
    图像：<input type="file" class="img" /><br />
    <button>点击发送ajax传送文件</button>
    <script>
      let userEle = document.querySelector(".username");
      let imgEle = document.querySelector(".img");
      let btn = document.querySelector("button");
      btn.onclick = function () {
        let username = userEle.value;
        let imgfile = imgEle.files[0];
        // 1.需要借助 formData对象  2.不需要设置头部；
        // 通过一个form data对象 来存储 数据和文件；
        let form = new FormData();
        // 把数据和文件加入到form
        form.append("username", username);
        form.append("img", imgfile);
        let xhr = new XMLHttpRequest();
        xhr.open("POST", "file.php");
        xhr.onload = function () {
          console.log(xhr.responseText);
        };
        xhr.send(form);
      };
    </script>
  </body>
</html>
